<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>广播管理 - 币胜客pro</title>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="trading-modal.css">
  <style>
    /* 广播管理页面专用样式 */
    .broadcast-container {
      min-height: 100vh;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      padding: 20px;
    }
    
    .broadcast-content-wrapper {
      margin-top: 80px;
    }
    
    /* 创建分组模态框输入框样式 */
    .create-group-input {
      pointer-events: auto !important;
      user-select: text !important;
      -webkit-user-select: text !important;
      -moz-user-select: text !important;
      -ms-user-select: text !important;
      background: #fff !important;
      color: #0f172a !important;
      border: 1px solid rgba(15,23,42,.12) !important;
      outline: none !important;
      box-shadow: none !important;
    }
    
    .create-group-input:focus {
      border-color: #0ea5e9 !important;
      box-shadow: 0 0 0 3px rgba(14,165,233,.15) !important;
    }
    
    .create-group-input:disabled {
      background: #f8fafc !important;
      color: #64748b !important;
      cursor: not-allowed !important;
    }
    
    .broadcast-header {
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(10px);
      border-radius: 20px;
      padding: 30px;
      margin-bottom: 30px;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
    
    .broadcast-title {
      font-size: 2.5rem;
      font-weight: 700;
      color: white;
      margin: 0 0 10px 0;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    }
    
    .broadcast-subtitle {
      font-size: 1.1rem;
      color: rgba(255, 255, 255, 0.8);
      margin: 0;
    }
    
    .broadcast-content {
      display: flex;
      justify-content: center;
      align-items: flex-start;
      margin-bottom: 30px;
    }
    
    .broadcast-section {
      max-width: 500px;
      width: 100%;
      background: rgba(255, 255, 255, 0.95);
      border-radius: 15px;
      padding: 25px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
    
    .section-title {
      font-size: 1.5rem;
      font-weight: 600;
      color: #1f2937;
      margin: 0 0 20px 0;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .section-icon {
      font-size: 1.8rem;
    }
    
    .form-group {
      margin-bottom: 20px;
    }
    
    .form-label {
      display: block;
      font-weight: 500;
      color: #374151;
      margin-bottom: 8px;
    }
    
    .form-input, .form-select {
      width: 100%;
      padding: 12px 16px;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
      font-size: 14px;
      transition: border-color 0.3s ease;
    }
    
    .form-input:focus, .form-select:focus {
      outline: none;
      border-color: #3b82f6;
    }
    
    .btn {
      padding: 12px 24px;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s ease;
      display: inline-flex;
      align-items: center;
      gap: 8px;
    }
    
    .btn-primary {
      background: #3b82f6;
      color: white;
    }
    
    .btn-primary:hover {
      background: #2563eb;
      transform: translateY(-1px);
    }
    
    .btn-secondary {
      background: #6b7280;
      color: white;
    }
    
    .btn-secondary:hover {
      background: #4b5563;
    }
    
    .btn-success {
      background: #10b981;
      color: white;
    }
    
    .btn-success:hover {
      background: #059669;
    }
    
    .btn-danger {
      background: #ef4444;
      color: white;
    }
    
    .btn-danger:hover {
      background: #dc2626;
    }
    
    .btn-group {
      display: flex;
      gap: 12px;
      margin-top: 20px;
    }
    
    .back-btn {
      position: fixed;
      top: 20px;
      left: 20px;
      background: rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.3);
      color: white;
      padding: 12px 20px;
      border-radius: 50px;
      text-decoration: none;
      font-weight: 500;
      transition: all 0.3s ease;
      z-index: 1000;
    }
    
    .back-btn:hover {
      background: rgba(255, 255, 255, 0.3);
      transform: translateY(-2px);
    }
    
    
    
    .loading {
      text-align: center;
      padding: 40px;
      color: #6b7280;
    }
    
    .error {
      background: #fee2e2;
      color: #991b1b;
      padding: 12px;
      border-radius: 8px;
      margin: 10px 0;
    }
    
    .success {
      background: #d1fae5;
      color: #065f46;
      padding: 12px;
      border-radius: 8px;
      margin: 10px 0;
    }
    
    @media (max-width: 768px) {
      .broadcast-content {
        padding: 0 20px;
      }
      
      .broadcast-section {
        max-width: 100%;
        margin: 0 10px;
      }
      
      .broadcast-title {
        font-size: 2rem;
      }
    }
    
    /* 表单帮助文字样式 */
    .form-help {
      margin-top: 5px;
      font-size: 12px;
      color: #6c757d;
      font-style: italic;
    }
    
    /* 用户分配预览样式 */
    .allocation-preview {
      margin-top: 10px;
      padding: 15px;
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      font-size: 14px;
    }
    
    .allocation-preview h4 {
      margin: 0 0 10px 0;
      color: #495057;
      font-size: 16px;
    }
    
    .allocation-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #e9ecef;
    }
    
    .allocation-item:last-child {
      border-bottom: none;
    }
    
    .allocation-user {
      font-weight: 500;
      color: #495057;
    }
    
    .allocation-details {
      text-align: right;
      color: #6c757d;
    }
    
    .allocation-percentage {
      font-weight: 600;
      color: #007bff;
    }
    
    .allocation-amount {
      font-size: 12px;
      margin-top: 2px;
    }
  </style>
</head>
<body>
  <a href="admin.html" class="back-btn">← 返回管理台</a>
  
  <div class="broadcast-container">
    <div class="broadcast-content-wrapper">
      <!-- 页面头部 -->
      <div class="broadcast-header">
        <h1 class="broadcast-title">📡 广播管理</h1>
        <p class="broadcast-subtitle">管理广播订单、查看执行状态和统计信息</p>
      </div>
      
      
      <!-- 主要内容区域 -->
    <div class="broadcast-content">
      <!-- 广播下单 -->
      <div class="broadcast-section">
        <h2 class="section-title">
          <span class="section-icon">🚀</span>
          广播下单
        </h2>
        
        <form id="broadcast-form">
          <div class="form-group">
            <label class="form-label">交易符号</label>
            <input type="text" id="symbol" class="form-input" placeholder="如 BTC-USDT" required>
          </div>
          
          <div class="form-group">
            <label class="form-label">订单类型</label>
            <select id="order-type" class="form-select" required>
              <option value="market">市价单</option>
              <option value="limit">限价单</option>
              <option value="stop">止损单</option>
              <option value="stop_limit">止损限价单</option>
            </select>
          </div>
          
          <div class="form-group">
            <label class="form-label">交易方向</label>
            <select id="side" class="form-select" required>
              <option value="buy">买入</option>
              <option value="sell">卖出</option>
            </select>
          </div>
          
           <div class="form-group">
             <label class="form-label">投入百分比 (%)</label>
             <input type="number" id="quantity" class="form-input" placeholder="10" step="0.1" min="0" max="100" required>
             <div class="form-help">各用户将按此百分比投入各自资金</div>
             <div id="user-allocation-preview" class="allocation-preview" style="display: none;">
               <h4>用户分配预览</h4>
               <div id="allocation-list"></div>
             </div>
           </div>
          
          <div class="form-group" id="price-group" style="display: none;">
            <label class="form-label">价格</label>
            <input type="number" id="price" class="form-input" placeholder="50000" step="0.01" min="0">
          </div>
          
          <div class="form-group">
            <label class="form-label">广播组</label>
            <div style="display: flex; gap: 8px; align-items: center;">
              <select id="broadcast-group" class="form-select" required style="flex: 1;">
                <option value="">选择广播组...</option>
              </select>
              <button type="button" class="btn btn-success" onclick="createBroadcastGroup()" title="创建新分组">
                ➕
              </button>
              <button type="button" class="btn btn-secondary" onclick="viewGroupDetails(document.getElementById('broadcast-group').value)" title="查看分组详情">
                👁️
              </button>
              <button type="button" class="btn btn-danger" onclick="deleteBroadcastGroup(document.getElementById('broadcast-group').value)" title="删除分组">
                🗑️
              </button>
            </div>
          </div>
          
          <div class="btn-group">
            <button type="submit" class="btn btn-primary">
              📡 执行广播下单
            </button>
            <button type="button" class="btn btn-secondary" onclick="loadBroadcastGroups()">
              🔄 刷新广播组
            </button>
            <button type="button" class="btn btn-secondary" onclick="loadRiskConfig()">
              ⚙️ 风控配置
            </button>
          </div>
        </form>
        
        <div id="broadcast-result"></div>
      </div>
      
    </div>
    </div>
  </div>
  
  <script src="app.js"></script>
  <script src="admin.js"></script>
  <script>
    // 权限检查 - 确保只有管理员能访问
    async function checkAdminPermission() {
      try {
        var token = localStorage.getItem('token');
        if (!token) {
          alert('请先登录');
          window.location.href = 'index.html';
          return false;
        }
        
        // 获取用户信息
        var response = await fetch('http://43.153.150.144:8080/auth/me', {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/json'
          },
          credentials: 'include'
        });
        
        if (!response.ok) {
          throw new Error('获取用户信息失败: ' + response.status);
        }
        
        var userInfo = await response.json();
        console.log('用户信息:', userInfo);
        
        // 检查是否为管理员
        var isAdmin = !!(userInfo && (userInfo.role === 'admin' || userInfo.is_admin));
        console.log('管理员权限检查:', isAdmin);
        
        if (!isAdmin) {
          alert('您没有管理员权限，无法访问此页面');
          window.location.href = 'index.html';
          return false;
        }
        
        return true;
      } catch (err) {
        console.error('权限检查失败:', err);
        alert('权限检查失败: ' + err.message);
        window.location.href = 'index.html';
        return false;
      }
    }
    
    // 页面加载时检查权限
    document.addEventListener('DOMContentLoaded', async function() {
      var hasPermission = await checkAdminPermission();
      if (!hasPermission) {
        return;
      }
      
      // 权限检查通过，初始化页面
      initializePage();
    });
    
    // 初始化页面
    function initializePage() {
      console.log('初始化广播管理页面');
      loadBroadcastGroups();
      loadRecentOrders();
    }
    
    // 广播管理专用API请求函数
    async function broadcastRequest(method, path, data, isAdmin) {
      // 构建完整的API URL
      var baseUrl = 'http://43.153.150.144:8080'; // 使用实际的API服务器地址
      var url = baseUrl + path;
      
      // 如果是管理员API，添加/admin前缀
      if (isAdmin && !path.startsWith('/admin')) {
        url = baseUrl + '/admin' + path;
      }
      
      console.log('API请求:', method, url, data);
      
      // 获取认证token
      var token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未找到认证token，请先登录');
      }
      
      var options = {
        method: method,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer ' + token
        }
      };
      
      if (data) {
        options.body = JSON.stringify(data);
      }
      
      try {
        var response = await fetch(url, options);
        console.log('API响应状态:', response.status, response.statusText);
        
        // 检查响应内容类型
        var contentType = response.headers.get('content-type');
        console.log('响应内容类型:', contentType);
        
        // 204状态码表示成功但无内容，直接返回
        if (response.status === 204) {
          console.log('API返回204状态码，删除操作成功');
          return response;
        }
        
        if (contentType && contentType.includes('application/json')) {
          return response;
        } else {
          // 如果响应不是JSON，抛出错误
          var text = await response.text();
          console.error('API返回非JSON响应:', text);
          throw new Error('API返回了非JSON格式的响应: ' + response.status);
        }
      } catch (err) {
        console.error('API请求失败:', err);
        throw err;
      }
    }

    // 广播管理页面状态
    var broadcastState = {
      broadcastGroups: []
    };

    // API连接测试函数
    async function testApiConnection() {
      console.log('=== API连接测试开始 ===');
      
      try {
        // 测试基本连接
        var testUrl = 'http://43.153.150.144:8080/docs';
        console.log('测试API文档端点:', testUrl);
        
        var response = await fetch(testUrl);
        console.log('API文档响应状态:', response.status);
        
        if (response.ok) {
          console.log('✅ API服务器连接正常');
        } else {
          console.log('⚠️ API服务器响应异常:', response.status);
        }
        
        // 订单API暂时不可用，跳过测试
        console.log('⚠️ 订单API暂时不可用，跳过测试');
        
      } catch (err) {
        console.log('❌ API服务器连接失败:', err.message);
      }
      
      console.log('=== API连接测试结束 ===');
    }

    // 更新用户分配预览
    async function updateUserAllocationPreview() {
      var percentage = parseFloat(document.getElementById('quantity').value);
      var groupId = document.getElementById('broadcast-group').value;
      var previewEl = document.getElementById('user-allocation-preview');
      var allocationListEl = document.getElementById('allocation-list');
      
      // 如果没有输入百分比或没有选择分组，隐藏预览
      if (!percentage || !groupId) {
        previewEl.style.display = 'none';
        return;
      }
      
      try {
        // 获取分组详情
        var response = await broadcastRequest('GET', '/admin/groups/' + groupId, null, true);
        if (response.ok) {
          var groupData = await response.json();
          console.log('分组详情:', groupData);
          
          if (groupData && groupData.members && groupData.members.length > 0) {
            // 生成分配预览HTML - 直接按各自资金乘百分比
            var html = '';
            groupData.members.forEach(function(member) {
              if (member.enabled) {
                // 每个用户都按相同百分比投入各自资金
                var allocatedPercentage = percentage.toFixed(1);
                
                html += '<div class="allocation-item">';
                html += '<div class="allocation-user">' + member.account_name + '</div>';
                html += '<div class="allocation-details">';
                html += '<div class="allocation-percentage">投入百分比: ' + allocatedPercentage + '%</div>';
                html += '<div class="allocation-amount">按各自资金计算</div>';
                html += '</div>';
                html += '</div>';
              }
            });
            
            allocationListEl.innerHTML = html;
            previewEl.style.display = 'block';
          } else {
            previewEl.style.display = 'none';
          }
        } else {
          previewEl.style.display = 'none';
        }
      } catch (err) {
        console.error('获取分组详情失败:', err);
        previewEl.style.display = 'none';
      }
    }
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
      console.log('广播管理页面已加载');
      
      // 测试API连接
      testApiConnection();
      
      // 加载广播组
      loadBroadcastGroups();
      
      // 加载统计信息
      
      // 加载订单历史
      
      // 监听订单类型变化
      document.getElementById('order-type').addEventListener('change', function() {
        var priceGroup = document.getElementById('price-group');
        if (this.value === 'limit' || this.value === 'stop_limit') {
          priceGroup.style.display = 'block';
        } else {
          priceGroup.style.display = 'none';
        }
      });
      
      // 监听百分比输入变化，显示用户分配预览
      document.getElementById('quantity').addEventListener('input', function() {
        updateUserAllocationPreview();
      });
      
      // 监听广播组选择变化，更新用户分配预览
      document.getElementById('broadcast-group').addEventListener('change', function() {
        updateUserAllocationPreview();
      });
      
      // 监听表单提交
      document.getElementById('broadcast-form').addEventListener('submit', function(e) {
        e.preventDefault();
        executeBroadcastOrder();
      });
    });
    
    // 加载广播统计
    
    
    // 执行广播下单
    async function executeBroadcastOrder() {
      try {
        console.log('执行广播下单');
        
        // 获取表单数据
        var symbol = document.getElementById('symbol').value.trim();
        var orderType = document.getElementById('order-type').value;
        var side = document.getElementById('side').value;
        var percentage = parseFloat(document.getElementById('quantity').value); // 现在是百分比
        var price = orderType === 'limit' ? parseFloat(document.getElementById('price').value) : null;
        var broadcastGroup = document.getElementById('broadcast-group').value;
        
        // 验证表单数据
        if (!symbol || !orderType || !side || !percentage || (orderType === 'limit' && !price)) {
          alert('请填写完整的订单信息');
          return;
        }
        
        if (percentage <= 0 || percentage > 100) {
          alert('投入百分比必须在0-100之间');
          return;
        }
        
        if (orderType === 'limit' && price <= 0) {
          alert('限价单价格必须大于0');
          return;
        }
        
        // 获取广播分组的关联交易所信息
        var groupExchange = null;
        try {
          var groupResponse = await broadcastRequest('GET', '/admin/groups/' + broadcastGroup, null, true);
          if (groupResponse.ok) {
            var groupData = await groupResponse.json();
            groupExchange = groupData.exchange || groupData.connector;
            console.log('广播分组关联交易所:', groupExchange);
          }
        } catch (err) {
          console.warn('获取广播分组信息失败，使用默认交易所:', err);
        }
        
        // 交易所选项到connector值的映射
        var exchangeToConnectorMap = {
          'gate_io': 'gate_io',
          'gate_io_perpetual': 'gate_io_perpetual',
          'binance': 'binance',
          'binance_perpetual': 'binance_perpetual',
          'okx': 'okx',
          'okx_perpetual': 'okx_perpetual',
          'huobi': 'huobi',
          'huobi_perpetual': 'huobi_perpetual',
          'bybit': 'bybit',
          'bybit_perpetual': 'bybit_perpetual',
          'kraken': 'kraken',
          'kraken_perpetual': 'kraken_perpetual',
          'coinbase': 'coinbase',
          'coinbase_perpetual': 'coinbase_perpetual',
          'kucoin': 'kucoin',
          'kucoin_perpetual': 'kucoin_perpetual'
        };
        
        // 根据关联交易所确定connector
        var connector = exchangeToConnectorMap[groupExchange] || 'gate_io'; // 默认使用gate_io
        console.log('使用的connector:', connector);
        
        // 构建广播下单数据 - 根据API文档格式
        var broadcastData = {
          group_id: parseInt(broadcastGroup), // 目标分组ID
          connector: connector, // 目标交易所连接器，需要在白名单内
          trade_type: side.toUpperCase(), // BUY/SELL
          order_type: orderType.toUpperCase(), // MARKET/LIMIT
          position_action: 'OPEN', // OPEN/CLOSE
          symbol: symbol, // 交易对（如 BTC-USDT）
          price: price || 0, // 限价价格，可省略表示市价
          invest_percent: percentage, // 投入百分比（10表示10%），系统按成员在交易所的权益乘百分比计算名义金额，再做风控归一化
          skip_unbound: false // 是否跳过未绑定目标connector的账户（默认false，拒单并提示）
        };
        
        console.log('广播下单数据:', broadcastData);
        
        // 显示加载状态
        var submitBtn = document.querySelector('#broadcast-form button[type="submit"]');
        var originalText = submitBtn.textContent;
        submitBtn.textContent = '执行中...';
        submitBtn.disabled = true;
        
        // 调用广播下单API
        var response = await broadcastRequest('POST', '/admin/broadcast', broadcastData, true);
        var result = await response.json();
        
        console.log('广播下单API响应:', result);
        
        if (response.ok) {
          // 检查API返回结果中是否包含错误
          if (result.results && Array.isArray(result.results)) {
            var hasErrors = result.results.some(function(item) {
              return item.status === 'error';
            });
            
            if (hasErrors) {
              // 有错误，显示错误信息
              var errorMsg = '广播下单失败！\n\n错误详情：\n';
              result.results.forEach(function(item) {
                if (item.status === 'error') {
                  errorMsg += '账户: ' + item.account_name + '\n';
                  errorMsg += '错误: ' + item.error + '\n\n';
                }
              });
              alert(errorMsg);
              return;
            }
          }
          
          // 构建成功提示信息
          var successMsg = '广播下单成功！\n\n投入百分比: ' + percentage + '%\n';
          successMsg += '交易对: ' + symbol + '\n';
          successMsg += '方向: ' + (side === 'buy' ? '买入' : '卖出') + '\n';
          successMsg += '类型: ' + (orderType === 'market' ? '市价单' : '限价单') + '\n';
          successMsg += '交易所: ' + connector + '\n';
          successMsg += '分配方式: 各用户按相同百分比投入各自资金\n';
          
          alert(successMsg);
          
          // 清空表单
          document.getElementById('broadcast-form').reset();
          
          // 隐藏用户分配预览
          document.getElementById('user-allocation-preview').style.display = 'none';
          
          // 刷新统计数据
          
          // 刷新订单历史
        } else {
          throw new Error(result.message || result.detail || '广播下单失败');
        }
      } catch (err) {
        console.error('广播下单失败:', err);
        alert('广播下单失败: ' + err.message);
      } finally {
        // 恢复按钮状态
        var submitBtn = document.querySelector('#broadcast-form button[type="submit"]');
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
      }
    }
    
    // 加载广播组 - 根据API文档调用真实接口
    async function loadBroadcastGroups() {
      try {
        console.log('加载广播分组列表');
        
        // 调用管理员广播分组列表API
        var response = await broadcastRequest('GET', '/admin/groups', null, true);
        console.log('广播分组API响应状态:', response.status);
        
        if (response.ok) {
          var groupsData = await response.json();
          console.log('广播分组数据:', groupsData);
          
          // 处理分页数据格式
          var groups = [];
          if (groupsData && Array.isArray(groupsData)) {
            // 直接数组格式
            groups = groupsData;
          } else if (groupsData && groupsData.items && Array.isArray(groupsData.items)) {
            // 分页对象格式 {total: 1, page: 1, page_size: 20, items: Array(1)}
            groups = groupsData.items;
          } else {
            throw new Error('API返回数据格式不正确');
          }
          
          if (groups.length > 0) {
            var selectEl = document.getElementById('broadcast-group');
            if (selectEl) {
              selectEl.innerHTML = '<option value="">选择广播组...</option>';
              
              groups.forEach(function(group) {
                var option = document.createElement('option');
                option.value = group.id;
                option.textContent = (group.name || '未命名分组') + ' (' + (group.members ? group.members.length : 0) + '人)';
                selectEl.appendChild(option);
              });
            }
            
            broadcastState.broadcastGroups = groups;
          } else {
            console.log('暂无广播分组数据');
          }
        } else {
          throw new Error('获取广播分组失败: ' + response.status);
        }
      } catch (err) {
        console.error('加载广播分组失败:', err);
        
        // 使用模拟数据作为备选
        var mockGroups = [
          { id: 'group1', name: '活跃用户组', member_count: 150 },
          { id: 'group2', name: 'VIP用户组', member_count: 50 },
          { id: 'group3', name: '测试用户组', member_count: 20 }
        ];
        
        var selectEl = document.getElementById('broadcast-group');
        if (selectEl) {
          selectEl.innerHTML = '<option value="">选择广播组...</option>';
          
          mockGroups.forEach(function(group) {
            var option = document.createElement('option');
            option.value = group.id;
            option.textContent = group.name + ' (' + group.member_count + '人)';
            selectEl.appendChild(option);
          });
        }
        
        broadcastState.broadcastGroups = mockGroups;
      }
    }
    
    // 创建广播分组
    async function createBroadcastGroup() {
      // 显示创建分组的模态框
      showCreateGroupModal();
    }
    
    // 显示创建分组模态框
    function showCreateGroupModal() {
      // 创建模态框容器
      var modal = document.createElement('div');
      modal.id = 'create-group-modal';
      modal.className = 'modal';
      modal.style.cssText = 'display: flex; z-index: 10000; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5);';
      
      // 创建模态框内容
      var modalContent = document.createElement('div');
      modalContent.className = 'modal-content';
      modalContent.style.cssText = 'max-width: 500px; z-index: 10001; position: relative; background: white; border-radius: 15px; margin: auto;';
      
      // 创建模态框头部
      var modalHeader = document.createElement('div');
      modalHeader.className = 'modal-header';
      modalHeader.innerHTML = `
        <div class="modal-icon">📡</div>
        <div>
          <h2 class="modal-title">创建广播分组</h2>
          <p class="modal-subtitle">设置分组信息和关联交易所</p>
        </div>
        <button class="modal-close" onclick="closeCreateGroupModal()">&times;</button>
      `;
      
      // 创建模态框主体
      var modalBody = document.createElement('div');
      modalBody.className = 'modal-body';
      modalBody.innerHTML = `
        <div class="form-group">
          <label class="form-label">分组名称</label>
          <input type="text" id="group-name" placeholder="请输入分组名称" required>
        </div>
        
        <div class="form-group">
          <label class="form-label">分组描述</label>
          <textarea id="group-description" placeholder="请输入分组描述" rows="3"></textarea>
        </div>
        
        <div class="form-group">
          <label class="form-label">
            <span class="label-icon">🏦</span>
            关联交易所
            <span class="help-icon" title="用户必须绑定此交易所才能加入该分组">?</span>
          </label>
          <select id="group-exchange" required>
            <option value="">选择交易所...</option>
            <option value="gate_io_spot">Gate.io 现货</option>
            <option value="gate_io_futures">Gate.io 合约</option>
            <option value="binance_spot">Binance 现货</option>
            <option value="binance_futures">Binance 合约</option>
            <option value="okx_spot">OKX 现货</option>
            <option value="okx_futures">OKX 合约</option>
            <option value="huobi_spot">Huobi 现货</option>
            <option value="huobi_futures">Huobi 合约</option>
            <option value="bybit_spot">Bybit 现货</option>
            <option value="bybit_futures">Bybit 合约</option>
            <option value="kraken_spot">Kraken 现货</option>
            <option value="kraken_futures">Kraken 合约</option>
            <option value="coinbase_spot">Coinbase 现货</option>
            <option value="coinbase_futures">Coinbase 合约</option>
            <option value="kucoin_spot">KuCoin 现货</option>
            <option value="kucoin_futures">KuCoin 合约</option>
          </select>
        </div>
        
        <div class="form-actions">
          <button class="btn-secondary" onclick="closeCreateGroupModal()">取消</button>
          <button class="btn-primary" onclick="submitCreateGroup()">创建分组</button>
        </div>
      `;
      
      // 组装模态框
      modalContent.appendChild(modalHeader);
      modalContent.appendChild(modalBody);
      modal.appendChild(modalContent);
      
      // 添加点击背景关闭功能
      modal.addEventListener('click', function(e) {
        if (e.target === modal) {
          closeCreateGroupModal();
        }
      });
      
      // 添加到页面
      document.body.appendChild(modal);
      
      // 确保输入框可以正常使用
      setTimeout(function() {
        var nameInput = document.getElementById('group-name');
        var descInput = document.getElementById('group-description');
        var exchangeSelect = document.getElementById('group-exchange');
        
        console.log('创建分组模态框输入框已激活');
        console.log('输入框元素:', { nameInput, descInput, exchangeSelect });
        
        // 测试输入框是否可编辑
        testCreateGroupInputs();
      }, 100);
    }
    
    // 关闭创建分组模态框
    function closeCreateGroupModal() {
      var modal = document.getElementById('create-group-modal');
      if (modal) {
        modal.remove();
      }
    }
    
    // 提交创建分组
    async function submitCreateGroup() {
      var groupName = document.getElementById('group-name').value.trim();
      var groupDescription = document.getElementById('group-description').value.trim();
      var groupExchange = document.getElementById('group-exchange').value;
      
      if (!groupName) {
        alert('请输入分组名称');
        return;
      }
      
      if (!groupExchange) {
        alert('请选择关联交易所');
        return;
      }
      
      try {
        console.log('创建广播分组:', groupName, '关联交易所:', groupExchange);
        
        // 交易所选项到connector值的映射
        var exchangeToConnectorMap = {
          'gate_io_spot': 'gate_io',
          'gate_io_futures': 'gate_io_perpetual',
          'binance_spot': 'binance',
          'binance_futures': 'binance_perpetual',
          'okx_spot': 'okx',
          'okx_futures': 'okx_perpetual',
          'huobi_spot': 'huobi',
          'huobi_futures': 'huobi_perpetual',
          'bybit_spot': 'bybit',
          'bybit_futures': 'bybit_perpetual',
          'kraken_spot': 'kraken',
          'kraken_futures': 'kraken_perpetual',
          'coinbase_spot': 'coinbase',
          'coinbase_futures': 'coinbase_perpetual',
          'kucoin_spot': 'kucoin',
          'kucoin_futures': 'kucoin_perpetual'
        };
        
        // 将交易所选项转换为对应的connector值
        var connectorValue = exchangeToConnectorMap[groupExchange] || groupExchange;
        console.log('创建广播组 - 原始选择:', groupExchange, '转换后的connector:', connectorValue);
        
        var groupData = {
          name: groupName,
          desc: groupDescription,
          connector_name: connectorValue // 使用转换后的connector值
        };
        
        var response = await broadcastRequest('POST', '/admin/groups', groupData, true);
        console.log('创建分组API响应状态:', response.status);
        
        if (response.ok) {
          var result = await response.json();
          console.log('创建分组响应数据:', result);
          alert('广播分组创建成功！\n关联交易所: ' + getExchangeDisplayName(groupExchange) + '\nConnector: ' + connectorValue);
          
          // 关闭模态框
          closeCreateGroupModal();
          
          // 重新加载分组列表
          loadBroadcastGroups();
        } else {
          var errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.message || errorData.detail || '创建分组失败: ' + response.status);
        }
      } catch (err) {
        console.error('创建分组失败:', err);
        alert('创建分组失败: ' + err.message);
      }
    }
    
    // 获取交易所显示名称
    function getExchangeDisplayName(exchangeId) {
      var exchanges = {
        'gate_io_spot': 'Gate.io 现货',
        'gate_io_futures': 'Gate.io 合约',
        'binance_spot': 'Binance 现货',
        'binance_futures': 'Binance 合约',
        'okx_spot': 'OKX 现货',
        'okx_futures': 'OKX 合约',
        'huobi_spot': 'Huobi 现货',
        'huobi_futures': 'Huobi 合约',
        'bybit_spot': 'Bybit 现货',
        'bybit_futures': 'Bybit 合约',
        'kraken_spot': 'Kraken 现货',
        'kraken_futures': 'Kraken 合约',
        'coinbase_spot': 'Coinbase 现货',
        'coinbase_futures': 'Coinbase 合约',
        'kucoin_spot': 'KuCoin 现货',
        'kucoin_futures': 'KuCoin 合约'
      };
      return exchanges[exchangeId] || exchangeId;
    }
    
    // 测试创建分组输入框
    function testCreateGroupInputs() {
      var nameInput = document.getElementById('group-name');
      var descInput = document.getElementById('group-description');
      var exchangeSelect = document.getElementById('group-exchange');
      
      console.log('测试创建分组输入框:');
      console.log('- 分组名称输入框:', nameInput ? '存在' : '不存在');
      console.log('- 分组描述输入框:', descInput ? '存在' : '不存在');
      console.log('- 交易所选择框:', exchangeSelect ? '存在' : '不存在');
      
      if (nameInput) {
        console.log('- 分组名称输入框状态:', {
          disabled: nameInput.disabled,
          readOnly: nameInput.readOnly,
          pointerEvents: nameInput.style.pointerEvents,
          userSelect: nameInput.style.userSelect
        });
        
        // 强制激活输入框
        nameInput.removeAttribute('disabled');
        nameInput.removeAttribute('readonly');
        nameInput.setAttribute('contenteditable', 'true');
        nameInput.style.pointerEvents = 'auto';
        nameInput.style.userSelect = 'text';
        nameInput.style.webkitUserSelect = 'text';
        nameInput.style.mozUserSelect = 'text';
        nameInput.style.msUserSelect = 'text';
      }
      
      if (descInput) {
        console.log('- 分组描述输入框状态:', {
          disabled: descInput.disabled,
          readOnly: descInput.readOnly,
          pointerEvents: descInput.style.pointerEvents,
          userSelect: descInput.style.userSelect
        });
        
        // 强制激活输入框
        descInput.removeAttribute('disabled');
        descInput.removeAttribute('readonly');
        descInput.setAttribute('contenteditable', 'true');
        descInput.style.pointerEvents = 'auto';
        descInput.style.userSelect = 'text';
        descInput.style.webkitUserSelect = 'text';
        descInput.style.mozUserSelect = 'text';
        descInput.style.msUserSelect = 'text';
      }
      
      if (exchangeSelect) {
        console.log('- 交易所选择框状态:', {
          disabled: exchangeSelect.disabled,
          pointerEvents: exchangeSelect.style.pointerEvents
        });
        
        // 强制激活选择框
        exchangeSelect.removeAttribute('disabled');
        exchangeSelect.style.pointerEvents = 'auto';
      }
      
      // 尝试强制聚焦到第一个输入框
      if (nameInput) {
        nameInput.focus();
        nameInput.click();
        console.log('已尝试聚焦到分组名称输入框');
      }
    }
    
    // 删除广播分组
    async function deleteBroadcastGroup(groupId) {
      if (!confirm('确认删除此广播分组？此操作不可撤销。')) {
        return;
      }
      
      try {
        console.log('删除广播分组:', groupId);
        
        var response = await broadcastRequest('DELETE', '/admin/groups/' + groupId, null, true);
        console.log('删除分组API响应状态:', response.status);
        
        if (response.ok || response.status === 204) {
          console.log('删除分组成功');
          alert('广播分组删除成功！');
          
          // 重新加载分组列表
          loadBroadcastGroups();
        } else {
          var errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.message || errorData.detail || '删除分组失败: ' + response.status);
        }
      } catch (err) {
        console.error('删除分组失败:', err);
        alert('删除分组失败: ' + err.message);
      }
    }
    
    // 查看分组详情
    async function viewGroupDetails(groupId) {
      try {
        console.log('查看分组详情:', groupId);
        
        var response = await broadcastRequest('GET', '/admin/groups/' + groupId, null, true);
        console.log('分组详情API响应状态:', response.status);
        
        if (response.ok) {
          var groupData = await response.json();
          console.log('分组详情数据:', groupData);
          
          // 显示分组详情
          var details = '分组名称: ' + (groupData.name || '未命名') + '\n';
          details += '分组描述: ' + (groupData.desc || '无描述') + '\n';
          details += '成员数量: ' + (groupData.members ? groupData.members.length : 0) + '\n';
          details += '创建时间: ' + (groupData.created_at || '未知') + '\n';
          details += '更新时间: ' + (groupData.updated_at || '未知');
          
          alert(details);
        } else {
          var errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.message || errorData.detail || '获取分组详情失败: ' + response.status);
        }
      } catch (err) {
        console.error('获取分组详情失败:', err);
        alert('获取分组详情失败: ' + err.message);
      }
    }
    
    // 加载风控配置
    async function loadRiskConfig() {
      try {
        console.log('加载广播风控配置');
        
        var response = await broadcastRequest('GET', '/admin/risk-config', null, true);
        console.log('风控配置API响应状态:', response.status);
        
        if (response.ok) {
          var configData = await response.json();
          console.log('风控配置数据:', configData);
          
          // 显示风控配置信息
          var configInfo = '广播风控配置:\n';
          if (configData.max_order_amount) {
            configInfo += '最大订单金额: ' + configData.max_order_amount + '\n';
          }
          if (configData.max_daily_orders) {
            configInfo += '每日最大订单数: ' + configData.max_daily_orders + '\n';
          }
          if (configData.risk_level) {
            configInfo += '风险等级: ' + configData.risk_level + '\n';
          }
          if (configData.enabled) {
            configInfo += '风控状态: ' + (configData.enabled ? '启用' : '禁用');
          }
          
          alert(configInfo);
        } else {
          var errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.message || errorData.detail || '获取风控配置失败: ' + response.status);
        }
      } catch (err) {
        console.error('获取风控配置失败:', err);
        alert('获取风控配置失败: ' + err.message);
      }
    }
    
    
    // 全局API测试函数 - 可在控制台中调用
    window.testBroadcastAPI = function() {
      console.log('=== 广播管理API测试 ===');
      return testApiConnection();
    };
    
    // 全局重新加载函数
    window.reloadBroadcastData = function() {
      console.log('重新加载广播管理数据...');
      loadBroadcastGroups();
    };
    
    // 测试所有广播管理API
    window.testAllBroadcastAPIs = async function() {
      console.log('=== 广播管理API全面测试开始 ===');
      
      try {
        // 测试基本连接
        await testApiConnection();
        
        // 测试广播分组列表
        console.log('测试广播分组列表API...');
        await loadBroadcastGroups();
        
        // 测试风控配置
        console.log('测试风控配置API...');
        await loadRiskConfig();
        
        // 测试统计数据
        console.log('测试统计数据API...');
        await loadBroadcastStats();
        
        // 测试订单历史
        console.log('测试订单历史API...');
        await loadOrderHistory();
        
        console.log('✅ 所有广播管理API测试完成');
        return { success: true, message: '所有API测试完成' };
      } catch (err) {
        console.error('❌ 广播管理API测试失败:', err);
        return { success: false, error: err.message };
      } finally {
        console.log('=== 广播管理API全面测试结束 ===');
      }
    };
    
    // 创建测试分组
    window.createTestGroup = async function() {
      try {
        var testGroupData = {
          name: '测试分组_' + new Date().getTime(),
          desc: '这是一个测试分组，用于验证API功能'
        };
        
        var response = await broadcastRequest('POST', '/admin/groups', testGroupData, true);
        if (response.ok) {
          var result = await response.json();
          console.log('✅ 测试分组创建成功:', result);
          loadBroadcastGroups(); // 刷新列表
          return result;
        } else {
          throw new Error('创建测试分组失败: ' + response.status);
        }
      } catch (err) {
        console.error('❌ 创建测试分组失败:', err);
        return { success: false, error: err.message };
      }
    };

    // 测试API接口
    window.testApiEndpoints = async function() {
      console.log('=== 测试API接口 ===');
      
      try {
        // 测试广播分组接口
        console.log('测试 /admin/groups 接口...');
        var groupsResponse = await broadcastRequest('GET', '/admin/groups', null, true);
        console.log('广播分组响应状态:', groupsResponse.status);
        
        if (groupsResponse.ok) {
          var groupsData = await groupsResponse.json();
          console.log('广播分组原始数据:', groupsData);
          console.log('数据类型:', typeof groupsData);
          console.log('是否为数组:', Array.isArray(groupsData));
          
          if (groupsData && groupsData.items) {
            console.log('分页格式 - items数量:', groupsData.items.length);
            console.log('分页信息:', {
              total: groupsData.total,
              page: groupsData.page,
              page_size: groupsData.page_size
            });
          }
        } else {
          console.error('广播分组API调用失败:', groupsResponse.status, groupsResponse.statusText);
        }
        
      } catch (error) {
        console.error('API测试失败:', error);
      }
    };
    
    // 调试广播分组加载
    window.debugBroadcastGroups = async function() {
      console.log('=== 调试广播分组加载 ===');
      
      try {
        var token = localStorage.getItem('token');
        console.log('当前token:', token ? '已设置' : '未设置');
        
        var response = await broadcastRequest('GET', '/admin/groups', null, true);
        console.log('API响应状态:', response.status);
        console.log('API响应头:', response.headers);
        
        if (response.ok) {
          var data = await response.json();
          console.log('API响应数据:', data);
          console.log('数据格式分析:');
          console.log('- 是否为数组:', Array.isArray(data));
          console.log('- 是否有items属性:', data && data.items !== undefined);
          console.log('- items是否为数组:', data && data.items && Array.isArray(data.items));
          
          if (data && data.items) {
            console.log('分页数据详情:');
            console.log('- 总数:', data.total);
            console.log('- 当前页:', data.page);
            console.log('- 每页大小:', data.page_size);
            console.log('- 项目数量:', data.items.length);
            console.log('- 项目详情:', data.items);
          }
        } else {
          var errorText = await response.text();
          console.error('API错误响应:', errorText);
        }
      } catch (err) {
        console.error('调试过程中出错:', err);
      }
    };
  </script>
</body>
</html>
